﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace CollegeWebsite.Web.Common
{
    public class MvcMenu : Controller
    {
        public Dictionary<string, string> GetAllActions()
        {
            var menuLink = new Dictionary<string, string>();

            // Get all Area Routes if any in projects
           

            var allAreaRoutes = Assembly.GetCallingAssembly().GetTypes().Where(area => area.BaseType != null && area.BaseType == typeof(AreaRegistration));

            var allControler = Assembly.GetCallingAssembly().GetTypes().Where(type => type.IsSubclassOf(typeof(ControllerBase))).ToList();
            
            foreach (var area in allAreaRoutes)
            {
                foreach (var controler in allControler)
                {
                    var methods = controler.GetMethods(BindingFlags.Public | BindingFlags.Instance);
                    foreach (var methodInfo in methods)
                    {
                        if (methodInfo.ReturnType == typeof(ActionResult) && (methodInfo.GetParameters().Length == 0 || methodInfo.GetParameters()[0].Name == "ajax"))
                        {
                            string link = ""; string methodDisplayName = "";
                            if (area.Namespace != null && (controler.Namespace != null && controler.Namespace.StartsWith(area.Namespace)))
                            {
                                link += area.Name.Replace("AreaRegistration", "");
                            }
                            link += "/" + controler.Name.Replace("Controller", "") + "/" + methodInfo.Name+"/";

                            var methodDisplaynameAttribute =
                                (DisplayNameAttribute)
                                Attribute.GetCustomAttributes(methodInfo, typeof (DisplayNameAttribute)).FirstOrDefault();
                            if (methodDisplaynameAttribute != null)
                                methodDisplayName = methodDisplaynameAttribute.DisplayName; 
                            
                            menuLink.Add(link, methodDisplayName);
                        }
                    }
                   
                }
            }
            return menuLink;
        }
    }
}
